﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using HotDealD2.Models.ModelView;
using HotDealD2.Models.ModelManager;
using HotDealD2.Models.Repository;
using HotDealD2.Models;
using HotDealD2.Helper;
namespace HotDealD2.Controllers
{
    public class AccountController : Controller
    {
        public CustomRoleProvider AuthorizationService { get; set; }
        AccountModel account;
        protected override void Initialize(RequestContext requestContext)
        {
            if (AuthorizationService == null)
                AuthorizationService = new CustomRoleProvider();
            account = new AccountModel();
            base.Initialize(requestContext);
        }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            LogonView lgView = new LogonView();
            
            return View(lgView);

        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogonView logOnView)
        {
            if (ModelState.IsValid)
            {
                AccountModel account = new AccountModel();
                if (account.CheckLogon(logOnView.UserName, logOnView.Password))
                {
                    
                    Session["LogOn"] = logOnView.UserName;
                    FormsAuthentication.SetAuthCookie(logOnView.UserName, logOnView.RememberMe);
                    switch (AuthorizationService.GetRolesForUser(logOnView.UserName)[0])
                    {
                        case "Admin":
                            return RedirectToAction("Index", "Admin");
                        case "Business":
                            return RedirectToAction("ListPromotion", "Business");
                        case "Member":
                            return RedirectToAction("Index", "Member");
                    }                    
                }
                else
                {
                    ModelState.AddModelError("", "Tên tài khoản hoặc mật khẩu không đúng");
                }
               
            }
            

            // If we got this far, something failed, redisplay form
            return View();
        }

       

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            Session["Cart" + Session["LogOn"]] = null;
            Session["LogOn"] = null;
            
            FormsAuthentication.SignOut();
            
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            
            IList<TinhThanh> listTinhThanh = account.GetAllTinhThanh();
            var model = new RegisterView();
            // TODO: this list probably comes from a repository or something
            var lTinhThanh = new SelectList(listTinhThanh, "MaTinhThanh", "TenTinhThanh", model.SelectedCity);
            model.CityList = lTinhThanh;
            IList<QuanHuyen> listQuanHuyen = account.GetAllQuanHuyen(1);
            var lQuanHuyen = new SelectList(listQuanHuyen, "MaQuanHuyen", "TenQuanHuyen", model.SelectedDistrict);
            model.DistrictList = lQuanHuyen;
            return View(model);
        
        }

        //
        // POST: /Account/Register
        [HttpPost]
        public ActionResult Register(RegisterView regisView)
        {
            
            if (ModelState.IsValid)
            {
                
                if (!account.IsUserLoginIDExist(regisView.UserName))
                {
                    if (!account.IsEmailAddressExist(regisView.Email))
                    {
                        bool result = account.InsertAccount(regisView);
                        if (result)
                        {
                            if (account.CheckLogon(regisView.UserName, regisView.Password))
                            {
                                Session["LogOn"] = regisView.UserName;
                                FormsAuthentication.SetAuthCookie(regisView.UserName, false);

                                return RedirectToAction("Index", "Member");

                            }
                        }
                    }

                    else
                        ModelState.AddModelError("", "Địa chỉ E-mail đã tồn tại");
                }
                else
                {
                    ModelState.AddModelError("", "Ten Tai Khoan Da Ton Tai");
                }
            }
            IList<TinhThanh> listTinhThanh = account.GetAllTinhThanh();
            var lTinhThanh = new SelectList(listTinhThanh, "MaTinhThanh", "TenTinhThanh", regisView.SelectedCity);
            regisView.CityList = lTinhThanh;
            IList<QuanHuyen> listQuanHuyen = account.GetAllQuanHuyen(1);
            var lQuanHuyen = new SelectList(listQuanHuyen, "MaQuanHuyen", "TenQuanHuyen", regisView.SelectedDistrict);
            regisView.DistrictList = lQuanHuyen;
            return View(regisView);
        }

        //
        // GET: /Account/ChangePassword
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        
        //[Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordView view)
        {
            bool result = account.IsPassWordNotRight(Session["Logon"].ToString(), view.OldPassword);
            if (result)
            {

                if (ModelState.IsValid)
                {
                    account.UpdatePassWord(Session["Logon"].ToString(), view.NewPassword);
                    return RedirectToAction("ChangePassWordSuccess", "Account");

                }
                else
                {
                    return View(view);
                }


            }
            else
            {
                ModelState.AddModelError("", "Mật khẩu cũ không chính xác");
            }

            return View(view);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult UpdateAccountSuccess()
        {
            return View();
        }

        public ActionResult UpdateAccount(string username)
        {

            AccountModel account = new AccountModel();
            ThanhVien thanhvien = account.GetAccount(username);
            return View(thanhvien);
        }
        [HttpPost]
        public ActionResult UpdateAccount(ThanhVien thanhvien,string username,FormCollection form)
        {
            AccountModel account = new AccountModel();
             Boolean kq =false;
            thanhvien.NguoiDung.TinhThanh = Int32.Parse(form.Get("tinh").ToString());
            thanhvien.NguoiDung.QuanHuyen = Int32.Parse(form.Get("quan").ToString());
            if(form.Get("remember_me")!=null)
                kq= Boolean.Parse(form.Get("remember_me"));
            if(kq==true)
            thanhvien.DangKyDoanhNghiep =true;
            else
                if (kq == false)
                thanhvien.DangKyDoanhNghiep = false;
            bool result = account.UpdateAccount(thanhvien);
            if (result == true)
            {
                return RedirectToAction("Index", "Member");
            }
            return View();
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
